package lucene.server.web.controller.admin;


import lombok.extern.slf4j.Slf4j;
import lucene.server.web.dao.UserDao;
import lucene.server.web.model.LoginUser;
import lucene.server.common.model.Result;
import lucene.server.web.dao.SystemDao;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;


@RestController
@RequestMapping("/admin/login")
@Slf4j
public class LoginController {

    @PostMapping(value = "/login")
    public Result<?> login(@RequestBody LoginUser user, HttpServletRequest req) {
        LoginUser dbLoginUser = UserDao.getUser(user.getUsername());
        if (dbLoginUser == null){
            return Result.error("用户名或密码错误");
        }else if (!"admin".equals(dbLoginUser.getType())){
            return Result.error("用户不支持登录");
        }else if (!dbLoginUser.getPassword().equals(user.getPassword())){
            return Result.error("用户名或密码错误");
        }else{
            user.setToken(UUID.randomUUID().toString().replace("-", ""));
            UserDao.modifyToken(user);
            return  Result.OK(user.getToken() );
        }
    }
    @PostMapping(value = "/checkToken")
    public Result<?> checkToken(@RequestBody LoginUser loginUser, HttpServletRequest req) {

        if (loginUser ==null || loginUser.getToken() == null){
            return Result.error("token无效，请重新登录");
        }  else if (UserDao.checkToken(loginUser.getToken())== null){
            return Result.error("token失效，请重新登录");
        }else{
            return  Result.OK(loginUser.getToken() );
        }

    }

}

